from django.http import HttpResponse, JsonResponse
from django.shortcuts import render
import os

from app5.forms import UserInfoForm, UserInfo_Msg_Form, ImgFileForm, UserInfoModelForm
from app5.models import ImgFile


# Create your views here.
def upload_file(request):
    if request.method == 'GET':
        return render(request,"5/upload.html")
    elif request.method == 'POST':
        myFile = request.FILES.get('myFile',None)
        if myFile is not None:
            # 二进制写操作
            path = 'media/uploads/'
            if not os.path.exists(path):
                os.makedirs(path)
            dest =  open(os.path.join(path + myFile.name),'wb+')
            # 分块写入文件
            for chunk in myFile.chunks():
                dest.write(chunk)
            dest.close()
            return HttpResponse("上传完成")
    else:
        return HttpResponse("没有上传文件")

def userinfo_form(request):
    if request.method == 'GET':
        myForm = UserInfoForm()
        return render(request,'5/userinfo.html',{'form_obj':myForm})
# 使用模型表单
def userinfo_model_form(request):
    if request.method == 'GET':
        myForm = UserInfoModelForm()
        return render(request,'5/userinfoform.html',{'form_obj':myForm})
    else:
        f = UserInfoModelForm(request.POST)
        if f.is_valid():
            print(f.clean())
            print(f.cleaned_data["username"])
            print(f.data)
        else:
            errors = f.errors
            print(errors)
            return render(request, "5/userinfoform.html", {'form_obj': f, 'errors': errors})
        return render(request, "5/userinfoform.html", {'form_obj': f})

def userinfo_msg_form(request):
    if request.method == 'GET':
        myForm = UserInfo_Msg_Form()
        return render(request,"5/userinfoform.html",{'form_obj':myForm})
    else:
        f = UserInfo_Msg_Form(request.POST)
        if f.is_valid():
            # clean:获取全部 数据，以字典方式返回
            # cleaned_data["username"]：标识回去数据中的username字段内容
            # data:以QueryDict字典返回
            print(f.clean()) # {'username': 'admin66', 'password': '111111', 'age': 18, 'mobile': '13955462104', 'status': '0', 'createdate': None}
            print(f.cleaned_data["username"]) # admin66
            print(f.data) # 表单原始数据 <QueryDict: {'csrfmiddlewaretoken': ['nBRfK6MB8GokEFR5PjrkIUdeyByL2Sp32mZSeVifwapcxou8WsqBeAARPzpKLVDK'], 'username': ['admin66'], 'password': ['111111'], 'status': ['0'], 'age': ['18'], 'mobile': ['13955462104']}>
        else:
            errors = f.errors
            print(errors)
            return render(request,"5/userinfoform.html",{'form_obj':f})
    return render(request,'5/userinfoform.html',{'form_obj':f})

def img_file_form(request):
    if request.method == 'GET':
        f = ImgFileForm()
        return render(request,"5/upload_form.html",{'form_obj':f})
    else:
        f = ImgFileForm(request.POST, request.FILES)
        if f.is_valid():
            name = f.cleaned_data["name"]
            headimg = f.cleaned_data["headimg"]
            user = ImgFile()
            user.name = name
            user.headimg = headimg
            user.save()
            print("上传成功")
            return render(request,"5/upload_form.html",{'form_obj':f,'user':user})

def ajax_login(request):
    return render(request,"5/ajax_login.html")
def ajax_login_data(request):
    # 获取用户名和密码
    username = request.POST.get('username')
    password = request.POST.get('password')
    # 判断并返回JSON数据
    if username == 'admin' and password == '123456':
        return JsonResponse({'code':1,"msg":"登录成功"})
    else:
        return JsonResponse({'code':0,'msg':'登录失败'})